package com.example.asus.picselector.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.asus.picsel.EduMyPictureSelectorActivity;
import com.example.asus.picsel.Utils;
import com.example.asus.picselector.constants.Constants;
import com.example.asus.picselector.listener.OnItemClickListener;
import com.example.asus.picselector.R;
import com.example.asus.picselector.widget.RxPermissionManager;
import com.example.asus.picselector.adapter.UploadPicAdapter;
import com.example.asus.picselector.bean.UploadPicInfo;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private Button picSelectorBtn,picTailoringBtn;
    private ImageView picTailoringImg;
    private RecyclerView picSelectRlv;
    private UploadPicAdapter uploadPicAdapter;
    private GridLayoutManager gridLayoutManager;
    private List<UploadPicInfo> uploadPicInfoList; //选中图片集合
    private List<String> picUrlList; //图片路径集合
    private UploadPicInfo uploadPicInfo; //图片选择入口
    private String substring;
    String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA
    };

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        initData();
        initView();
        setListener();
    }

    public void initData(){
        uploadPicInfoList = new ArrayList<>();
        picUrlList = new ArrayList<>();
        uploadPicInfo = new UploadPicInfo();
        uploadPicInfoList.add(uploadPicInfo);
    }

    public void initView(){
        picSelectorBtn = findViewById(R.id.pic_selector_btn);
        picTailoringBtn = findViewById(R.id.pic_tailoring_btn);
        picTailoringImg = findViewById(R.id.img_pic_tailoring);
        picSelectRlv = findViewById(R.id.rlv_upload_pic);
        uploadPicAdapter = new UploadPicAdapter(this);
        gridLayoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        picSelectRlv.setLayoutManager(gridLayoutManager);
        picSelectRlv.setAdapter(uploadPicAdapter);
        uploadPicAdapter.setData(uploadPicInfoList);
    }

    public void setListener(){
        picSelectorBtn.setOnClickListener(this);
        picTailoringBtn.setOnClickListener(this);

        RxPermissionManager.getIntance().setPermissionsSuccessCallBack(new RxPermissionManager.PermissionsSuccessCallBack() {
            @Override
            public void success(int type) {
                Intent intent = new Intent(MainActivity.this, EduMyPictureSelectorActivity.class);
                switch (type){
                    case Constants.PIC_SELECTOR: //最多选择Constants.PIC_MAX_NUMEBR张图片
                        intent.putExtra(Constants.PIC_SEND,"完成");
                        intent.putExtra(Constants.PIC_ISSELECT,true);
                        intent.putExtra(Constants.PIC_MAX_SELECT,(uploadPicInfoList.size() - 1));
                        intent.putExtra(Constants.PIC_MAX,(Constants.PIC_MAX_NUMEBR - uploadPicInfoList.size()) >= 0 ?
                                (Constants.PIC_MAX_NUMEBR - uploadPicInfoList.size()) : (Constants.PIC_MAX_NUMEBR - 1));
                        startActivityForResult(intent,Constants.PIC_SELECT_RESULT);
                        break;
                    case Constants.PIC_TAILORING://图片裁剪
                        // 用户已经同意该权限
                        intent.putExtra(Constants.PIC_EDIT,true);
                        startActivityForResult(intent,Constants.PIC_TAILORING_RESULT);
                        break;
                }

            }
        });

        uploadPicAdapter.setDeletePicUrlListener(new UploadPicAdapter.DeletePicUrlListener() {
            @Override
            public void deletePicUrl(int posotion) {
                if(posotion > 0 && posotion < picUrlList.size() && picUrlList != null)
                    picUrlList.remove(posotion);
            }
        });

        uploadPicAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (uploadPicInfoList.size() - 1 == position) {  //系统相册
                    if(uploadPicInfoList.size() < Constants.PIC_MAX_NUMEBR){
                        RxPermissionManager.getIntance().checkPermissions(MainActivity.this,needPermissions,Constants.PIC_SELECTOR);
                    }else {
                        Toast.makeText(MainActivity.this,"最多选择"+(Constants.PIC_MAX_NUMEBR - 1)+"张图片哦!",Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Intent intent = new Intent(MainActivity.this, PhotoViewActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("dataBean", (ArrayList<String>) picUrlList);
                    intent.putExtras(bundle);
                    intent.putExtra("currentPosition", position);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    public void onClick(View view) {
       switch (view.getId()){
           case R.id.pic_selector_btn:
               substring = "";
               if(uploadPicInfoList.size() == 0){
                   uploadPicInfoList.add(uploadPicInfo);
               }
               if(uploadPicInfoList.size() < Constants.PIC_MAX_NUMEBR){
                   RxPermissionManager.getIntance().checkPermissions(this,needPermissions,Constants.PIC_SELECTOR);
               }else {
                   Toast.makeText(MainActivity.this,"最多选择"+(Constants.PIC_MAX_NUMEBR - 1)+"张图片哦!",Toast.LENGTH_SHORT).show();
               }
               break;
           case R.id.pic_tailoring_btn:
               uploadPicInfoList.clear();
               uploadPicAdapter.notifyDataSetChanged();
               RxPermissionManager.getIntance().checkPermissions(this,needPermissions,Constants.PIC_TAILORING);
               break;
       }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK && data != null){
            switch (requestCode){
                case Constants.SETTING_PERSSIOM:
                    Toast.makeText(this,"权限设置完成!",Toast.LENGTH_SHORT).show();
                    break;
                case Constants.PIC_SELECT_RESULT:
                    ArrayList<Uri> list1 = (ArrayList<Uri>) data.getSerializableExtra("android.intent.extra.RETURN_RESULT");
                    picSelectRlv.setVisibility(View.VISIBLE);
                    picTailoringImg.setVisibility(View.GONE);
                    for (int i = 0; i < list1.size(); i++) {
                        addListData(list1.get(i).toString().substring(6, list1.get(i).toString().length()));
                    }
                    break;
                case Constants.PIC_TAILORING_RESULT:
                    ArrayList<Uri> list2 = (ArrayList<Uri>) data.getSerializableExtra("android.intent.extra.RETURN_RESULT");
                    picSelectRlv.setVisibility(View.GONE);
                    picTailoringImg.setVisibility(View.VISIBLE);
                    substring = list2.get(0).toString().substring(6, list2.get(0).toString().length());
                    String picImgUrl = Utils.compressImage(substring);
                    Glide.with(this)
                            .load("file://"+ picImgUrl)
                            .centerCrop()
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .into(picTailoringImg);
                    Utils.deleteDirectory(Constants.TEMPORARY_PIC,picImgUrl,false);
                    break;
            }
        }

    }

    /**
     * 刷新布局
     * @param imagePath
     */
    private void addListData(String imagePath) {
        UploadPicInfo uploadPic = new UploadPicInfo(imagePath);
        uploadPicInfoList.add(0, uploadPic);
        picUrlList.add(0,imagePath);
        uploadPicAdapter.notifyDataSetChanged();
    }
}
